package com.ziyun.erp.modules.production.operate;

import com.cloud.bus.core.EventBusPusher;
import com.cloud.bus.event.order.OrderMessageEvent;
import com.utility.New;
import com.utility.StringUtils;
import com.ziyun.erp.common.e.order.OrderItemStatusEnum;
import com.ziyun.erp.common.e.order.PayStatusEnum;
import com.ziyun.erp.common.e.order.ProductionStatusEnum;
import com.ziyun.erp.common.e.order.PromotionTypeEnum;
import com.ziyun.erp.common.utils.ErpOrderUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.order.entity.ErpOrderEntity;
import com.ziyun.erp.modules.order.entity.OrderInfoEntity;
import com.ziyun.erp.modules.order.entity.OrderItemEntity;
import com.ziyun.erp.modules.order.service.ErpOrderService;
import com.ziyun.erp.modules.order.service.OrderInfoService;
import com.ziyun.erp.modules.order.service.OrderItemService;
import com.ziyun.erp.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.erp.modules.production.operate.entity.AllotStateEntity;
import com.ziyun.erp.modules.production.operate.entity.AuditStateEntity;
import com.ziyun.erp.modules.production.operate.entity.LogisticsStateEntity;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author guizhao
 * @Title: 待审核状态
 * @ProjectName ziyun-service-erp
 * @date 2018-09-08 15:12
 */
public class WaitAuditState implements ErpOrderState {

    private static Logger logger = LoggerFactory.getLogger(WaitAuditState.class);
    private ErpOrderService erpOrderService = SpringContextUtils.getBean("erpOrderService", ErpOrderService.class);
    private ErpOrderItemService erpOrderItemService = SpringContextUtils.getBean("erpOrderItemService", ErpOrderItemService.class);
    private OrderItemService orderItemService = SpringContextUtils.getBean("orderItemService", OrderItemService.class);
    OrderInfoService orderInfoService = SpringContextUtils.getBean("orderInfoService", OrderInfoService.class);

    @Override
    public R audit(AuditStateEntity auditStateEntity) {
        logger.info("=================order audit start====================");
        logger.info("=================order audit params：" + auditStateEntity.toString());

        String orderId = auditStateEntity.getOrderId();
        OrderInfoEntity orderInfoEntity = orderInfoService.selectById(orderId);
        Integer itemId = auditStateEntity.getItemId();
        Map<String, Object> updateMap = new HashMap<>();
        ErpOrderEntity erpOrderEntity  = erpOrderService.selectById(orderId);
        if (erpOrderEntity != null){
            Integer productionStatus = erpOrderEntity.getProductionStatus();
            if (productionStatus.intValue() != ProductionStatusEnum.UN_AUDITED.toInt()){
                return R.error("订单状态异常！");
            }
            ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.selectByItemId(itemId);
            Integer status = erpOrderItemEntity.getStatus();
            if (status.intValue() != OrderItemStatusEnum.UN_AUDITED.toInt()){
                return R.error("商品状态异常！");
            }
            Integer eoItemId = erpOrderItemEntity.getEoItemId();
            updateMap.put("status", OrderItemStatusEnum.UN_ALLOTED.toInt());
            erpOrderItemService.updateByMap(updateMap, eoItemId);
        }else {
            erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfoEntity);
            erpOrderService.insert(erpOrderEntity);

            List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.valueOf(orderId));
            List<ErpOrderItemEntity> erpOrderItemEntityList = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntityList, orderId);
            ErpOrderItemEntity erpOrderItemEntity = null;
            if (erpOrderItemEntityList.size() > 1){
                List<ErpOrderItemEntity> collect = erpOrderItemEntityList.stream()
                        .filter(o -> o.getOriginalItemId().intValue() == itemId.intValue())
                        .collect(Collectors.toList());
                erpOrderItemEntity = collect.get(0);
            }else {
                erpOrderItemEntity = erpOrderItemEntityList.get(0);
            }
            erpOrderItemEntity.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
            erpOrderItemService.insertBatch(erpOrderItemEntityList);
        }

        updateMap.clear();
        updateMap.put("auditName", UserUtils.getCurentUser().getUserId().toString());
        updateMap.put("auditTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        // 检查商品是否都已审核，若是，修改订单状态为待分配，若是企业集采订单，需修改支付状态为待支付，同时抛出事件
        boolean result = erpOrderItemService.operateErpOrderItemStatus(orderId, OrderItemStatusEnum.UN_ALLOTED.toInt());
        if (result){
            // 发送订单审核事件
            OrderMessageEvent event = new OrderMessageEvent(this, Long.valueOf(erpOrderEntity.getMemberId()), orderId, "audit");
            EventBusPusher.syncPost(event);
            String promotionType = orderInfoEntity.getPromotionType();
            if (StringUtils.equals(promotionType, PromotionTypeEnum.PROCUREMENT.toCode())){
                Map<String, Object> orderMap = New.hashMap();
                orderMap.put("payStatus", PayStatusEnum.NOT_PAY_0.toCode());
                orderInfoService.updateByMap(orderMap, orderId);
                updateMap.put("payStatus", PayStatusEnum.NOT_PAY_0.toCode());
            }
            updateMap.put("productionStatus", ProductionStatusEnum.UN_ALLOT.toInt());
        }
        erpOrderService.updateByMap(updateMap, orderId);

        logger.info("=================order audit end====================");
        return R.ok();
    }

    @Override
    public R allot(AllotStateEntity allotStateEntity) {
        return R.error("不支持操作！");
    }

    @Override
    public R receive(Integer productionId) {
        return R.error("不支持操作！");
    }

    @Override
    public R addLogistics(LogisticsStateEntity logisticsStateEntity, String userId, String createName) {
        return R.error("不支持操作！");
    }

    @Override
    public R allotPriceFinish(Integer productionId) {
        return R.error("不支持操作！");
    }

    @Override
    public R cancleAllot(Integer productionId) {
        return R.error("不支持操作！");
    }
}
